import React, { useState, useEffect } from "react";
import {
  Table,
  Form,
  Input,
  Button,
  Row,
  Col,
  Drawer,
  Tabs,
  Radio,
  Popconfirm,
  message,
  Typography,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { addAuth } from "../../../api/auth/index";
import PubSub from "pubsub-js";
const createTableData = [
  {
    action: "query",
    name: "查询列表",
    describe: "查询列表",
  },
  {
    action: "get",
    name: "查询明细",
    describe: "查询明细",
  },
  {
    action: "add",
    name: "新增",
    describe: "新增",
  },
  {
    action: "update",
    name: "修改",
    describe: "修改",
  },
  {
    action: "delete",
    name: "删除",
    describe: "删除",
  },
  {
    action: "import",
    name: "导入",
    describe: "导入",
  },
  {
    action: "export",
    name: "导出",
    describe: "导出",
  },
];
function CreateAuth() {
  //操作配置列表useState
  const [
    operationalConfigurationList,
    setOperationalConfigurationList,
  ] = useState(createTableData);
  const handleAdd = () => {
    tableForm.setFieldsValue({
      action: "",
      name: "",
      describe: "",
    });
    const newData = {
      action: "",
      name: "",
      describe: "",
    };
    setOperationalConfigurationList([...operationalConfigurationList, newData]);
  };
  useEffect(() => {
    PubSub.unsubscribe("showCreate");
    PubSub.subscribe("showCreate", (msg, state) => {
      setIsCreateJurisdiction(state);
      setOperationalConfigurationList(createTableData);
    });
  });
  const [tableForm] = Form.useForm();
  const [editingKey, setEditingKey] = useState("");
  const isEditing = (record) => record.action === editingKey;

  const EditableCell = ({ editing, dataIndex, title, children }) => {
    // console.log("edtablecell--------------------------------",{editing, dataIndex, title, children});
    const inputNode = <Input />;
    return (
      <td>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
            rules={
              dataIndex !== "describe"
                ? [
                    {
                      required: true,
                      message: `请输入${title}!`,
                    },
                  ]
                : [{}]
            }
          >
            {inputNode}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  const cancel = () => {
    setEditingKey("");
  };
  const save = async (key) => {
    try {
      const row = await tableForm.validateFields();
      const newData = [...operationalConfigurationList];
      const index = newData.findIndex((item) => key === item.action);

      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setOperationalConfigurationList(newData);
        setEditingKey("");
      } else {
        newData.push(row);
        setOperationalConfigurationList(newData);
        setEditingKey("");
      }
    } catch (errInfo) {
      console.log("Validate Failed:", errInfo);
    }
  };

  const edit = (record) => {
    tableForm.setFieldsValue({
      action: "",
      name: "",
      describe: "",
      ...record,
    });
    setEditingKey(record.action);
  };

  const createTableCol = [
    {
      title: "操作类型",
      dataIndex: "action",
      key: "action",
      editable: true,
    },
    {
      title: "名称",
      dataIndex: "name",
      key: "name",
      editable: true,
    },
    {
      title: "描述",
      dataIndex: "describe",
      key: "describe",
      editable: true,
    },
    {
      title: (
        <>
          {"操作 | "}
          <PlusOutlined onClick={handleAdd} />
        </>
      ),
      dataIndex: "operates",
      key: "operates",
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Popconfirm
              title="确认保存吗?"
              okText="确定"
              cancelText="取消"
              onConfirm={() => save(record.action)}
            >
              <a
                href="javascript:;"
                style={{
                  marginRight: 8,
                }}
              >
                保存
              </a>
            </Popconfirm>
            |
            <Button
              onClick={() => {
                console.log("取消");
                cancel();
              }}
              style={{ marginLeft: "10px" }}
              type="link"
            >
              取消
            </Button>
          </span>
        ) : (
          <Typography.Link disabled={editingKey !== ""}>
            <a
              href="javascript:;"
              style={{ marginRight: "10px" }}
              onClick={() => edit(record)}
            >
              {"编辑"}
            </a>
            |
            <Popconfirm
              title="确认删除吗?"
              okText="确定"
              cancelText="取消"
              onConfirm={() => {
                setOperationalConfigurationList(
                  operationalConfigurationList.filter(
                    (item) =>
                      item.action !== record.action &&
                      item.describe !== record.describe &&
                      item.name !== record.name
                  )
                );
              }}
            >
              <a href="javascript:;" style={{ marginLeft: "10px" }}>
                {"删除"}
              </a>
            </Popconfirm>
          </Typography.Link>
        );
      },
    },
  ];
  const mergedColumns = createTableCol.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: "text",
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  //是否创建权限useState
  const [isCreateJurisdiction, setIsCreateJurisdiction] = useState(false);

  const { TabPane } = Tabs;
  const [createForm] = Form.useForm();
  const onCreateJurisdiction = (values) => {
    values["describe"] = "";
    values["actions"] = operationalConfigurationList;
    let addData = addAuth(values);
    addData.then((item) => {
      message.success(item["msg"]);
      PubSub.publish("reset", true);
    });
    onClose();
  };

  const onClose = () => {
    createForm.resetFields();
    setIsCreateJurisdiction(false);
  };
  return (
    <Drawer
      title="新建权限"
      placement="right"
      width={"60%"}
      onClose={onClose}
      visible={isCreateJurisdiction}
      footer={
        <>
          <Button
            onClick={onClose}
            style={{ borderRadius: "4px", marginRight: "10px" }}
          >
            关闭
          </Button>
          <Button
            htmlType="submit"
            style={{ borderRadius: "4px" }}
            type="primary"
            onClick={() => {
              createForm.submit();
            }}
          >
            保存
          </Button>
        </>
      }
      footerStyle={{ textAlign: "right" }}
    >
      <Tabs defaultActiveKey="1">
        <TabPane tab="基本信息" key="1">
          <Form form={createForm} onFinish={onCreateJurisdiction}>
            <Row>
              <Col span={10} offset={2}>
                <Form.Item
                  rules={[
                    {
                      required: true,
                      message: "只能由字母数字下划线组成",
                      pattern: new RegExp("^[A-Za-z0-9_]+$"),
                    },
                  ]}
                  label="权限标识(ID)"
                  name="id"
                >
                  <Input
                    style={{ borderRadius: "6px" }}
                    placeholder="只能由字母数字下划线组成"
                  />
                </Form.Item>
              </Col>
              <Col span={9} offset={2}>
                <Form.Item
                  rules={[{ required: true, message: "请输入权限名称" }]}
                  label="权限名称"
                  name="name"
                >
                  <Input style={{ borderRadius: "6px" }} />
                </Form.Item>
              </Col>
              <Col span={8} offset={4}>
                <Form.Item
                  rules={[{ required: true, message: "请选择状态" }]}
                  label="状态"
                  name="status"
                >
                  <Radio.Group buttonStyle="solid">
                    <Radio.Button
                      style={{ borderRadius: "6px 0px 0px 6px" }}
                      value={1}
                    >
                      启用
                    </Radio.Button>
                    <Radio.Button
                      style={{ borderRadius: "0px 6px 6px 0px" }}
                      value={0}
                    >
                      禁用
                    </Radio.Button>
                  </Radio.Group>
                </Form.Item>
              </Col>
            </Row>
          </Form>
          <Form form={tableForm} component={false}>
            <Table
              size="small"
              components={{
                body: {
                  cell: EditableCell,
                },
              }}
              title={() => {
                return "操作配置";
              }}
              bordered={true}
              columns={mergedColumns}
              dataSource={operationalConfigurationList}
              pagination={{ onChange: cancel }}
            />
          </Form>
        </TabPane>
      </Tabs>
    </Drawer>
  );
}

export default CreateAuth;
